<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JWT鉴权测试</title>
</head>
<body>
<h2>JWT登录测试</h2>
<div>
    <label>用户名：<input id="username" type="text" value="user"></label><br>
    <label>密码：<input id="password" type="password" value="1234"></label><br>
    <button onclick="login()">登录</button>
</div>

<p id="tokenDisplay"></p>

<div>
    <button onclick="accessHello()">访问/hello</button>
    <p id="helloResult"></p>
</div>

<script>
    let token = "";

    function login() {
      const username = document.getElementById("username").value;
      const password = document.getElementById("password").value;

      fetch("/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ username, password })
      })
      .then(res => {
        if (!res.ok) throw new Error("登录失败");
        return res.json();
      })
      .then(data => {
        token = data.token;
        document.getElementById("tokenDisplay").innerText = "Token: " + token;
      })
      .catch(err => {
        document.getElementById("tokenDisplay").innerText = "登录失败：" + err.message;
      });
    }

    function accessHello() {
      fetch("/hello", {
        headers: {
          "Authorization": "Bearer " + token
        }
      })
      .then(res => {
        if (!res.ok) throw new Error("访问失败");
        return res.text();
      })
      .then(text => {
        document.getElementById("helloResult").innerText = text;
      })
      .catch(err => {
        document.getElementById("helloResult").innerText = "访问失败：" + err.message;
      });
    }
</script>
</body>
</html>
